var watched = new Array();
var scrollItems = 2;
var hideSlideVar;
var car_params = {
					responsive: true,
					width: '100%',
					height: 105,
					auto: false,
					scroll: {
						items: scrollItems,
						duration: 1000,
						easing: "easeOutExpo"
					},
					items: {
						width: 146,
						height: 80,
						visible: {
							max: 'auto'
						}
					},
					wipe: {
						onTouch: true,
						onMouse: true
					},
					mousewheel: {
						//items: scrollItems
					}/*,
					synchronise : [".another-b-elements .b-elements"]*/
	};
	
$(function() {
	/*var margin = Math.round((parseInt($('.b-slide').width()) - parseInt($('#bigPreview').attr('width'))) / 2) + 168;
	$('.bigVideoPreviewDiv').css({marginLeft: '-' + margin + 'px'});*/
	
	/* неверно!
	var left = (100 - (Math.round((parseInt($('.b-slide').width()) + parseInt($('.slide-side').width())) / parseInt($('.over-b-slide').width()) * 100))) * 3;
	console.log(parseInt($('.over-b-slide').width()));
	$('.bigVideoPreviewDiv').css({left: left + '%'});*/
	
	/*var left = Math.round(parseInt($('.over-b-slide').width()) * 0.5 / (parseInt($('.b-slide').width()))  * 50 - 1);
	console.log(parseInt($('.over-b-slide').width()));
	$('.bigVideoPreviewDiv').css({left: left + '%'});*/
	
	_V_('#bigPreview').ready(function(){
					var myPlayer = this;
					myPlayer.volume(0)
					myPlayer.play();
					hideSlideVar = setTimeout(function() {hideSlide(1000);}, 20000);
				});
	
	
	var catsNumber = 5;
	var parallax = 101;
	
	var catBlocks = new Object();
	catBlocks.catNum = 0;
	catBlocks.getCategoryName = function(index) {
		for(var cat in this)
		{
			if(this[cat].index == index)
				return cat;
		}
	};
	createCatsObject(catBlocks);
	
	if ($('#bigPreview_flash_api').size() > 0)
	{	
		$('#bigPreview_flash_api param[name=bgcolor]').remove();
		$('#bigPreview_flash_api').append('<param name="bgcolor" value="#EDEDED" />'); 
	}
	
	//setMainMargins(1500);
	setAllPageMargins(1500);
	
	//$(".peMopho").peMopho();
	
	//$('.btn a').click(function () {sendOrder($(this)); return false;});
	$('.orderDiv').modalPopLite({ openButton: '.btn a', closeButton: '.tclose' });
	
	$('#all_pages').on('mousewheel', '.another-b-elements', function(event, delta) {
		console.log(delta);
		if ($(this).hasClass('first-b-elements'))
		{
			console.log('yes');
			moveSliders($(this), delta);
		}
		else
		{
			console.log('no');
			moveSliders($(this).parents('.category').find('.first-b-elements'), delta);
		}
		return false;
	});
	
	$('.first-b-elements').each(function() {
		var elementCount = $(this).find('.element-item').size();
		var shiftStep = Math.round(elementCount/4);
		var shift = shiftStep;
		car_params.synchronise = [ '#' + $(this).parents('.category').attr('id') + " .another-b-elements .b-elements" ];
		$(this).carouFredSel(car_params);
		$(this).parents('.category').find('.another-b-elements .b-elements').each(function() {
			$(this).carouFredSel({
					responsive: true,
					width: '100%',
					height: 94,
					auto: false,
					items: {
						start: shift,
						width: 146,
						height: 70,
						visible: {
							max: 'auto'
						}
					}
			});
			shift += shiftStep;
		});
	});
	/*$('.first-b-elements').carouFredSel(car_params);
	$('.another-b-elements .b-elements').carouFredSel({
					responsive: true,
					width: '100%',
					height: 94,
					auto: false,
					items: {
						width: 146,
						height: 70,
						visible: {
							max: 'auto'
						}
					}
	});*/
	//$('.element-item').hover(playVideo, stopVideo);
	
	$('.mini-prew').carouFredSel({
					responsive: true,
					width: '40%',
					height: 36,
					auto: false,
					scroll: {
						duration: 150,
					},
					items: {
						width: 77,
						height: 36,
						visible: {
							min: 1,
							max: 'auto'
						}
					},
					wipe: {
						onTouch: true,
						onMouse: true
					},
					mousewheel: {
						items: 1
					}
	});
	
	//$('.mini-prew li').hover(darkImage, lightImage);
	$('.mini-prew').on('mouseenter', 'li', function() {$(this).addClass('active');});
	$('.mini-prew').on('mouseleave', 'li', function() {$(this).removeClass('active');});
	addAllWatched();
	
	//$('.element-item').click(function () { showVideoBlock($(this), parallax); });

	
	$(window).resize(resizeActivePage);
	//$('.hideSlideButton').click(hideSlide);
	$('.b-slide').click(function(){hideSlide(1000);});
	$('.logo').click(function() {
		showSlide();
	});
	//$('.slide-side').click(hideSlide);
	
	//Backbone--------------------------------------------------------------------------	
	var Controller = Backbone.Router.extend({
		routes: {
			"": "main",
			"!/": "main",
			"!/:page": "page",
			"!/category/:cat": "category",
			"!/tag/:tag": "tag",
			"!/tag/:tag/": "tag",
			"!/video/:video": "video",
			"!/tag/:tag/video/:video": "videoWithTag",
			"!/category/up/:cat/:num": "categoryUp"
        },
		
		categoryUp: function(cat, num) {
			//allBlocksDown(parallax, true);
			moveBlockUp(catBlocks, cat, num, parallax, true);
		},
		
		main: function() {
			if (!isActivePage('main'))
			{
				hideVideoBlock(false);
				hideTagBlock(false);
				allBlocksDown(parallax, false)
				$('#main').animate({right: '0%'}, 800, function() {
					$('.activePage').animate({right: '100%'}, 0, function() {
						$(this).removeClass('activePage');
						$('#main').addClass('activePage');
					});
				});
			}
			else
			{
				hideVideoBlock(isVideoBlockShown());
				hideTagBlock(isTagBlockShown());
				allBlocksDown(parallax, true);
			}
			
			//showSlide(false);
			
			//setTimeout(hideSlide, 6000);
			
			var an_logo = new Image();
			//an_logo.src = $('.slide-logo').css('backgound');
			an_logo.src = '/dev3/images/slide-logo.gif';
			/*an_logo.onload = function() {
				setTimeout(hideSlide, 10000);
			};*/
			
			/*hideVideoBlock(true);
			allBlocksDown(parallax, true);*/
			
			//moveBlockUp(catBlocks, 'titles', 3, parallax, true);
			/*$('.all_pages_block').hide("slide", { direction: "left" }, 1500);
			$('#main').show("slide", { direction: "right" }, 1500);*/
			/*$('.all_pages_block').slideUp(1500);
			$('#main').slideDown(1500);*/
			
			//$('#main').css({display:'block'});
			//$('#all_blocks').animate({left:'+' + $('#all_blocks').css('width')});
			/*$('.activePage').css({display:"none"});
			$('.activePage').removeClass('activePage');
			$('#main').addClass('activePage');*/
			
			/*if (!$('#main').hasClass('activePage'))
			{
				$('.activePage').css({zIndex:"100"});
				$('.activePage').removeClass('activePage');
				$('#main').addClass('activePage');
				$('.activePage').css({zIndex:"101"});
				$('#all_pages').animate({left: 0}, 1500);
			}*/
		},
		
		page: function(page) {
			//$('.over-b-slide').remove();
			hideSlide(0);
			/*$('.content_block').hide("slide", { direction: "left" }, 1000);
			$('#second').show("slide", { direction: "right" }, 1000);*/
			/*$('.content_block').slideUp(1500);
			$('#second').slideDown(1500);*/
			$('#' + page).css('height', $('#content').css('height'));
			if (!isActivePage(page))
			{
				$('#' + page).animate({right: '0%'}, 800, function() {
					$('.activePage').animate({right: '100%'}, 0, function() {
						$(this).removeClass('activePage');
						$('#' + page).addClass('activePage');
					});
				});
				
				$('#' + page).css('width', $('#content').css('width'));
			}
		},
		
		category: function(cat) {
			//$('.over-b-slide').remove();
			hideSlide(0);
			/*
				есть такой же кусок кода в main
				возможно стоит это как-то упростить
			*/
			if (!isActivePage('main'))
			{
				hideVideoBlock(false);
				hideTagBlock(false);
				showCategory(cat, catsNumber, parallax, false);
				$('#main').animate({right: '0%'}, 800, function() {
					$('.activePage').animate({right: '100%'}, 0, function() {
						$(this).removeClass('activePage');
						$('#main').addClass('activePage');
					});
				});
			}
			else
			{
				hideTagBlock(isTagBlockShown());
				hideVideoBlock(isVideoBlockShown());
				showCategory(cat, catsNumber, parallax, true);
			}
		},
		
		tag: function(tag) {
			//$('.over-b-slide').remove();
			hideSlide(0);
			if (!isActivePage('main'))
			{
				showTag(tag, false);
				$('#main').animate({right: '0%'}, 800, function() {
					$('.activePage').animate({right: '100%'}, 0, function() {
						$(this).removeClass('activePage');
						$('#main').addClass('activePage');
					});
				});
			}
			else
			{
				showTag(tag, true);
			}
				/*if (!isActivePage('tag'))
				{
					showTag(tag, false);
					$('#tag').animate({left: '0%'}, 1500, function() {
						$('.activePage').animate({left: '100%'}, 0, function() {
							$(this).removeClass('activePage');
							$('#tag').addClass('activePage');
						});
					});
				}
				else
				{
					showTag(tag, true);
				}*/
		},
		
		video: function(video) {
			//$('.over-b-slide').remove();
			hideSlide(0);
			/*
				есть такой же кусок кода в main
				возможно стоит это как-то упростить
			*/
			if (!isActivePage('main'))
			{
				hideVideoBlock(false);
				showVideoBlock2('video', video, parallax, false);
				$('#main').animate({right: '0%'}, 800, function() {
					$('.activePage').animate({right: '100%'}, 0, function() {
						$(this).removeClass('activePage');
						$('#main').addClass('activePage');
					});
				});
				addWatchedVideo(video);
			}
			else
			{
				showVideoBlock2('video', video, parallax, true);
				addWatchedVideo(video);
			}
			
		},
		
		videoWithTag: function(tag, video)
		{
			//???? нужна проверка на наличие тега
			//$('.over-b-slide').remove();
			hideSlide(0);
			if (!isActivePage('main'))
			{
				hideVideoBlock(false);
				showVideoBlock2('tagged_video', video, parallax, false);
				$('#main').animate({right: '0%'}, 800, function() {
					$('.activePage').animate({right: '100%'}, 0, function() {
						$(this).removeClass('activePage');
						$('#main').addClass('activePage');
					});
				});
			}
			else
			{
				//???? нужна проверка на наличие тега
				showVideoBlock2('tagged_video', video, parallax, true);
			}
		}
	});
	
	var controller = new Controller();

	Backbone.history.start();
});

function isTagBlockShown()
{
	if (parseInt($('#tag_page').css('top')) != 500)
		return true;
	return false;
}

function hideTagBlock(animate)
{
	var animateTime = 1500;
	
	if (!animate)
		animateTime = 0;
		
	$('#tag_page').animate({top: '500px'}, animateTime, function() {
		$(this).html('');
	});
	
}

function resizeActivePage()
{
	/*if (!$('#main').hasClass('activePage'))
		$('#all_pages').css('left', '-' + $('#all_pages').css('width'));*/
	/*if (isActivePage('main'))
		$('.category').css('width', $('#main').css('width'));*/
	//$('.activePage').css('width', $('#content').css('width'));
	//setMainMargins(0);
	setAllPageMargins(0);
}

function isActivePage(page_id)
{
	if ($('#' + page_id).hasClass('activePage'))
		return true;
	return false;
}

//console.log($('.category').eq(3).attr('class'));

function allBlocksDown(parallaxVal, animate)
{
	var one_parallax = 0;
	var animateTime = 800;
	
	if (!animate)
		animateTime = 0;
		
	$('.category').each(function() {
		$(this).animate({top: one_parallax}, animateTime);
		one_parallax += parallaxVal;
	});
}

/*
	(Array(object)) catObjects - ассоциативный массив объектов с описанием категорий
	(string) block - id сдвигаемого блока
	(int) upNum - количество позиций для сдвига
	(int) parallaxVal - высота одного слайдера
	(bool) animate - анимированный сдвиг (true) или нет (false)
*/

function moveBlockUp(catObjects, block, upNum, parallaxVal, animate)
{
	var firstCatID = '#' + $('.category').eq(0).attr('id');
	console.log(firstCatID);
	var blockID = '#' + block;
	var currentCatZindex = $(blockID).css('z-index');
	
	$(blockID).stop(false, false);
	//var upPixels = $(blockID).css('top') - upNum * parallaxVal;
	var futureIndex = 0;
	//var shift = upNum;
	if (catObjects[block].index > upNum)
	{
		futureIndex = catObjects[block].index - upNum;
	}
	/*else if (catObjects[block].index - upNum < 0)
	{
		shift = catObjects[block].index;
	}*/
			
	console.log(futureIndex);
		
	var upPixels = catObjects[block].index*parallaxVal - upNum * parallaxVal;
	
	if (upPixels < 0)
	{
		upPixels = 0;
	}
	
	var animateTime = 2000;
	
	if (!animate)
		animateTime = 0;
	
	$(blockID).animate({top: upPixels}, animateTime, function() {
		/*console.log(shift);
        for (var i=0; i!=shift; ++i) {
            var temp = catObjects[catObjects.getCategoryName(i)];
            for (var j=i; j!=catObjects.catNum-1; ++j) {
				console.log(j);
				catObjects[catObjects.getCategoryName(j)].zIndex = catObjects[catObjects.getCategoryName(j+1)].zIndex;
				catObjects[catObjects.getCategoryName(j)].index = catObjects[catObjects.getCategoryName(j+1)].index;
            }
           catObjects[catObjects.getCategoryName(catObjects.catNum-1)].index =  temp.index;
		   catObjects[catObjects.getCategoryName(catObjects.catNum-1)].zIndex = temp.zIndex;
        }
       
	   console.log(catObjects);
	   
	   var one_parallax = parallaxVal * shift + parseInt($(blockID).css('top'));
	   console.log(one_parallax);
	   $($(blockID).prevAll('.category').get().reverse()).each(function() {
			if ($(blockID).nextAll('.category').size() > 0)
			{
				$(blockID).nextAll('.category:last').after($(this));
			}
			else
			{
				$(blockID).after($(this));
			}
			
			$(this).animate({top: one_parallax}, animateTime);
			one_parallax += parallaxVal;
		});*/
	});
	//$(blockID).stop();
	//дальше смена свойств сдвигаемого объекта и тех, которые он перекрыл + их перемещение
}

function createCatsObject(object)
{
	$('.category').each(function() {
		var catID = $(this).attr('id');
		object[catID] = new Object();
		object[catID].zIndex = $(this).css('z-index');
		//object[catID].visibleRows = 1;
		object[catID].index = $(this).index();
		object.catNum++;
	});
}

function showVideoBlock(obj, parallaxVal) 
{
	console.log(obj.parents('.category').find('.video-wrap').css('display'));
	if (obj.parents('.category').find('.video-wrap').css('display') == 'none')
		hideVideoBlock(true);
	var video_id = obj.find('a').attr('href').split('/')[2];
	/*$('.video-wrap iframe').attr('src', 'http://player.vimeo.com/video/' + video_id + '?title=0&amp;byline=0&amp;portrait=0&amp;badge=0&amp;player_id=player&amp;api=1');
	obj.parents('.category').find('.row-category:first .row-title').after($('.video-wrap'));*/
	
	obj.parents('.category').find('.video-wrap iframe').attr('src', 'http://player.vimeo.com/video/' + video_id + '?title=0&amp;byline=0&amp;portrait=0&amp;badge=0&amp;player_id=player&amp;api=1');
	
	obj.parent('ul').trigger("slideTo", 
		[obj, "next", 1, {duration: 1500}]);
		
	//$('#main').before($('#video').animate({height: 'toggle', width: 'toggle'}, 2000));
	//$('#video').show('scale', {}, 2000);
	setTimeout(function() {obj.parents('.category').find('.video-wrap').show(2000, function() {
		$('.video-wrap .tags').show('fold', { direction: "right" }, 1000);
	});}, 1500);
	
	/*
		!!!
		если переход к видео будет происходить со страницы тега (или с люой другой страницы,
		которая не является главной)
		то категорию мне таким способом не узнать
		!!!!
	*/
	showCategory(obj.parents('.category').attr('id'), $('.category').size(),  parallaxVal, true);
	
	//$('#video').animate({height: 'toggle', width: 'toggle', top: 0}, 2000);
}

function getRandomArbitary(min, max)
{
  return Math.random() * (max - min) + min;
}

function showVideoBlock2(idText, id, parallaxVal, animate) 
{
	var obj = $('#' + idText + id);
	var classes_array = new Array('fc-rose', 'fc-dark', ' ');
	
	$.ajax({
		type: 'POST',
		url: '/controllers/get_video.php', 
		data: 'video_id=' + id, 
		success: function(data) { 
			//console.log(data);
			obj.parents('.category').find('.video-wrap iframe').attr('src', 'http://player.vimeo.com/video/' + data.vimeo_id + '?title=0&amp;byline=0&amp;portrait=0&amp;badge=0&amp;player_id=player&amp;api=1');

			var path = obj.parents('.category').find('.video-wrap');
			path.find('.name').text(data.code);
			path.find('.video_name').text(data.name);
			//path.find('.video_description').text(data.descr);
			if  (data.photo_num.length == 0)
				data.photo_num = '0';
			if  (data.text_num.length == 0)
				data.text_num = '0';	
			path.find('.photo_num').text(data.photo_num);
			path.find('.text_num').text(data.text_num);
			
			var tags_path = path.find('.tags ul');
			tags_path.html('');
			/*$('.b-tags .top').html('');
			$('.b-tags .bott').html('');*/
			var where = '.bott';
			var middle = Math.round(data.tags.length/2);
			var counter = 0;
			for (var key in data.tags) {
				/*if (counter == middle && middle > 3)
					where = '.top';
				var val = data.tags[key];*/
				tags_path.append('<li><a class="' + classes_array[Math.round(getRandomArbitary(0, 2))] + '" href="/#!/tag/' + data.tags[key].en_name + '">' + data.tags[key].ru_name + '</a></li>')
				/*$('.b-tags ' + where).append('<li><a class="' + classes_array[Math.round(getRandomArbitary(0, 2))] + '" href="/#!/tag/' + data.tags[key].en_name + '">' + data.tags[key].ru_name + '</a></li>');
				counter++;*/
			}

			var animateTime = 1500;
			
			if (!animate)
				animateTime = 0;
			
			
			//console.log(obj.parents('.category').find('.video-wrap').css('display'));
			if (obj.parents('.category').find('.video-wrap').css('display') == 'none')
				hideVideoBlock(true);
			
			//console.log(obj.html());
			var video_id = obj.find('a').attr('href').split('/')[obj.find('a').attr('href').split('/').length - 1];
			
			obj.parent('ul').trigger("slideTo", 
				[obj, "next", 1, {duration: animateTime}]);
				
			setTimeout(function() {obj.parents('.category').find('.video-wrap').show(animateTime + 500, function() {
				$('.video-wrap .tags').show('fold', { direction: "right" }, animateTime - 500);
			});}, animateTime);
			
			/*
				!!!
				если переход к видео будет происходить со страницы тега (или с люой другой страницы,
				которая не является главной)
				то категорию мне таким способом не узнать
				!!!!
			*/
			showCategory(obj.parents('.category').attr('id'), $('.category').size() + 2,  parallaxVal, animate);
		}, 
		dataType: 'json'
	});
	
	
}

function showCategory(cat, catsNumber, parallax, animate) 
{
	var blockID = '#' + cat;
			
	//$(blockID).stop(false, false);
				
	var upPixels = 0;			
	var animateTime = 800;
	
	if (!animate)
		animateTime = 0;
			
	$(blockID).animate({top: upPixels}, animateTime, function() {
		var currentZIndex = $(blockID).css('z-index');
		if ($(blockID).next('.category').size() > 0)
			$(blockID).css('z-index', $(blockID).next('.category').css('z-index'));
		var one_parallax_first;
		var newZIndex_first = catsNumber - currentZIndex + 2;
		$($(blockID).prevAll('.category').get().reverse()).each(function() {
			if ($(blockID).nextAll('.category').size() > 0)
			{
				$(blockID).nextAll('.category:last').after($(this));
			}
			else
			{
				$(blockID).after($(this));
			}
					
			one_parallax_first = parallax * (catsNumber - 2) + (newZIndex_first - 2) * parallax;
			$(this).animate({top: one_parallax_first}, 0);
			//$(this).css('z-index', newZIndex_first++);
		});
		
		var newZIndex_second = 3;
		var one_parallax_second = parallax * (catsNumber - 2);
		var nextCategory = $(blockID).next('.category').attr('id');
		$(blockID).next('.category').animate({top: one_parallax_second}, animateTime, function(){
			$(this).css('z-index', 2);
		});
		one_parallax_second += parallax;
		$(blockID).next('.category').nextAll('.category').each(function() {
			$(this).animate({top: one_parallax_second}, 0, function(){
				if (newZIndex_second + 1 >= 5)
					$(blockID).css('z-index', 1);
			});
			$(this).css('z-index', newZIndex_second++);
			one_parallax_second += parallax;;
		});
	});
}

function hideVideoBlock(animate)
{
	var animateTime = 1500;
	if (!animate)
		animateTime = 0;
		
	$('.video-wrap').slideUp(animateTime, function() {
		$('.video-wrap .tags').hide(animateTime);
	});
}

function darkImage()
{
	$(this).addClass('active');
}

function lightImage()
{
	$(this).removeClass('active');
}

/*function showTag(tag, animate)
{
	var animateTime = 2000;
	if (!animate)
		animateTime = 0;
		
	$('#tag').append($('#tag_template').html());
	$('.row-title a').text(tag);
	
	$('.tag_template_inside').slideDown(animateTime, function() {
		$('.tag_template_inside').prevAll().remove();
	});
}*/

function isVideoBlockShown()
{
	if ($('.video-wrap').css('display') == 'none')
		return false;
	else
		return true;
}

// возвращает cookie если есть или undefined
function getCookie(name) {
	var matches = document.cookie.match(new RegExp(
	  "(?:^|; )" + name.replace(/([\.$?*|{}\(\)\[\]\\\/\+^])/g, '\\$1') + "=([^;]*)"
	))
	return matches ? decodeURIComponent(matches[1]) : undefined 
}

// уcтанавливает cookie
function setCookie(name, value, props) {
	props = props || {}
	var exp = props.expires
	if (typeof exp == "number" && exp) {
		var d = new Date()
		d.setTime(d.getTime() + exp*1000)
		exp = props.expires = d
	}
	if(exp && exp.toUTCString) { props.expires = exp.toUTCString() }

	value = encodeURIComponent(value)
	var updatedCookie = name + "=" + value
	for(var propName in props){
		updatedCookie += "; " + propName
		var propValue = props[propName]
		if(propValue !== true){ updatedCookie += "=" + propValue }
	}
	document.cookie = updatedCookie

}

// удаляет cookie
function deleteCookie(name) {
	setCookie(name, null, { expires: -1 })
}


function hideSlide(time)
{
	clearTimeout(hideSlideVar);
	var animateTime = time;
	setCookie ('slideHide', true);
	//$('.over-b-slide').css('z-index', '110');
	_V_('#bigPreview').pause();
	
	$('.b-slide').animate({left: '-100%'}, animateTime, function(){
		//$('.over-b-slide').remove();
		$('.over-b-slide').css('z-index', '-1');
	});
}

function showSlide()
{
	clearTimeout(hideSlideVar);
	var animateTime = 1000;
	setCookie ('slideHide', true);
	_V_('#bigPreview').ready(function(){
					var myPlayer = this;
					myPlayer.currentTime(0);
					myPlayer.volume(0)
					myPlayer.play();
					hideSlideVar = setTimeout(function() {hideSlide(1000);}, 20000);
				});
	$('.over-b-slide').css('z-index', '110');
	//$('.over-b-slide').css('z-index', '0');
	
	$('.b-slide').animate({left: '0%'}, animateTime, function(){
		//$('.over-b-slide').remove();
	});
}

function playVideo()
{
	/*playerID = 'player' + playerID;
	
	var newObj = $('.video-frame').clone();
	newObj.attr('id', playerID);
	
	console.log($('body').prepend(newObj));
	
	$('#'+playerID).css('margin', (obj.offset().top - 5) + 'px 0px 0px' + (obj.offset().left - 5) + 'px');
	newObj.fadeIn();
	
	console.log((obj.offset().top - 5) + 'px 0px 0px ' + (obj.offset().left - 5) + 'px');*/
	
	//$f(document.getElementById(playerID)).addEvent('ready', ready);
	
	var preview = $(this).find('.video-frame');
	preview.fadeIn(1500);
	console.log(preview.find('iframe').attr('id'));
	$f(document.getElementById(preview.find('iframe').attr('id'))).addEvent('ready', ready)
}

function stopVideo()
{
	
	$(this).find('.video-frame').fadeOut('fast');
}

function moveSliders(obj, delta)
{
	if (delta < 0)
	{
		obj.trigger("next", scrollItems);
	}
	else
	{
		obj.trigger("prev", scrollItems);
	}
}

function showTag(tag, animate)
{
				var variables = {tag: tag};
				var template = _.template( $("#tag_template").html(), variables);
				$('#tag_page').append( template );
				var animateTime = 1500;
				
				if (!animate)
					animateTime = 0;
				
				$.ajax({
					type: 'POST',
					url: '/controllers/get_video_with_tag.php',
					data: 'tag_en=' + tag,
					success: function (data) {
						//console.log(data);
						
						for (var i = 0; i < data.video.length; i++)
						{
							$('.one_tag:last .first-b-elements').append('<li class="element-item" id = "tagged_video' + data.video[i].video_id + '"><a class="peMopho" href = "#!/tag/' + tag + '/video/' + data.video[i].video_id + '" video-file = "' + data.preview_dir + data.video[i].preview_id + '/' + data.video[i].preview_id + '.mp4" > <img src="' + data.preview_dir + data.video[i].preview_id + '/' + data.video[i].preview_id + '.jpg" alt="animated thumbnail" width="114" height="70" /></a></li>');
						}
						
						/*car_params.synchronise = [ '#' + $('.one_tag:last .first-b-elements').parents('.category').attr('id') + " .another-b-elements .b-elements" ];
						$('.one_tag:last .first-b-elements').carouFredSel(car_params);

						$('.one_tag:last .first-b-elements').parents('.category').find('.another-b-elements .b-elements').each(function() {
							$(this).carouFredSel({
									responsive: true,
									width: '100%',
									height: 94,
									auto: false,
									items: {
										width: 146,
										height: 70,
										visible: {
											max: 'auto'
										}
									}
							});
						});*/
						
						
						
							var elementCount = $('.one_tag:last .first-b-elements').find('.element-item').size();
							var shiftStep = Math.round(elementCount/4);
							if (shiftStep > 10)
								$('.one_tag:last .another-b-elements .b-elements').html($('.one_tag:last .first-b-elements').html());
							var shift = shiftStep;
							car_params.synchronise = [ '#tag_page .another-b-elements .b-elements' ];
							$('.one_tag:last .first-b-elements').carouFredSel(car_params);
							$('.one_tag:last .first-b-elements').parents('.category').find('.another-b-elements .b-elements').each(function() {
								$(this).carouFredSel({
										responsive: true,
										width: '100%',
										height: 94,
										auto: false,
										items: {
											start: shift,
											width: 146,
											height: 70,
											visible: {
												max: 'auto'
											}
										}
								});
								shift += shiftStep;
							});
						
						
						
						$('.one_tag:last .row-title a').text(data.tag_name);
						
						$('#tag_page').animate({top: parseInt($('#tag_page').css('top'), 10) - 500}, animateTime, function(){
							if ($('.one_tag').size() > 1)
							{
								var counter = 0;
								$('.one_tag').each(function() {
									if ($('.one_tag').size() == 1)
										return;
									$(this).remove();
									$('#tag_page').css('top', (parseInt($('#tag_page').css('top')) + 500) + 'px');
								});
							}
						});
					},
					dataType: 'json'
				});
}

function sendOrder(obj)
{
	//TINY.box.show({url:'/order.php',width:300,height:130});
	//TINY.box.show({url:'/upload/ind.php?art=' + obj.parents('.video-info').find('.prew .name').text(), width: 400, height: 480, top: 30, fixed: false/*, openjs: function() { bindFileUpload();}*/});
	//$( ".popupOrder" ).dialog();
	
	
	
	return false;
}

function setMainMargins(animateTime)
{
	var height = parseInt($('#main').height());
	var main_height = parseInt($('#main_conteiner').height());
	
	var margin = Math.round((height - main_height) / 2);
	
	$('#main').animate({paddingTop : margin + 'px'/*, marginBottom : margin + 'px'*/}, animateTime);
}

function setAllPageMargins(animateTime)
{
	var height = parseInt($('body').height());
	var header_height = parseInt($('#header').height());
	var footer_height = parseInt($('#footer').height());
	
	var main_height = parseInt($('#content').height());
	
	var margin = Math.round((height - main_height - header_height - footer_height) / 2);
	
	if (margin < 0)
		margin = 0;
		$('#content').animate({marginTop : margin + 'px'}, animateTime);
}

function addWatchedVideoCookie(video_id)
{
	//deleteCookie('watched');
	watched = getCookie('watched');
	
	if (watched == null || watched == 'undefined')
		watched = new Array();
	else
		watched = $.parseJSON(watched);
	
	/*console.log(watched);	
	console.log(watched.length);*/
	
	if (watched.length != 0 && $.inArray(video_id, watched) >= 0)
	{
		//console.log(watched);
		watched.splice(watched.indexOf(video_id),1);
		//console.log(watched);
		watched.unshift(video_id);
		setCookie('watched', JSON.stringify(watched), {expires: 604800});
		return false;
	}
	else
	{
		watched.unshift(video_id);
		setCookie('watched', JSON.stringify(watched), {expires: 604800});
		return true;
	}
}

function addAllWatched()
{
	watched = getCookie('watched');
	
	if (watched == null || watched == 'undefined')
		return false;
	else
		watched = $.parseJSON(watched);
		
	$.each(watched, function (index, value) {
		/*$.ajax({
			type: 'POST',
			url: '/controllers/get_vimeo_id.php',
			data: 'video_id=' + value,
			success: function(data) {
				var watchedHTML = '<li id = "miniVideo' + value + '"><a href="#!/video/' + value + '"><img src="/preview/' + data + '/' + data + '.jpg" alt="" width="57" height="36" /></a></li>';
				if ($('.mini-prew #miniVideo' + value).size() == 0)
					$(".mini-prew").trigger("insertItem", [watchedHTML, '.mini-prew li:first', true, 0]);
				e.preventDefault();
			}
		});*/
		var img = $('#video' + value + ' img').attr('src');
		var watchedHTML = '<li id = "miniVideo' + value + '"><a href="#!/video/' + value + '"><img src="' + img + '" alt="" width="57" height="36" /></a></li>'
		if ($('.mini-prew #miniVideo' + value).size() == 0)
			$(".mini-prew").trigger("insertItem", [watchedHTML, '.mini-prew li:first', true, 0]);
		//e.preventDefault();
	});
}

function addWatchedVideo(video_id)
{
	var add = addWatchedVideoCookie(video_id);
	/*$.ajax({
		type: 'POST',
		url: '/controllers/get_vimeo_id.php',
		data: 'video_id=' + video_id,
		success: function(data) {
			var watchedHTML = '<li id = "miniVideo' + video_id + '"><a href="#!/video/' + video_id + '"><img src="/preview/' + data + '/' + data + '.jpg" alt="" width="57" height="36" /></a></li>';
			//$('.mini-prew').append(watchedHTML);
			//if (!add)
			//	$(".mini-prew").trigger("removeItem", [$('.mini-prew #miniVideo' + video_id), true, 0]);
			if ($('.mini-prew #miniVideo' + video_id).size() == 0)
				$(".mini-prew").trigger("insertItem", [watchedHTML, '.mini-prew li:first', true, 0]);
			e.preventDefault();
		}
	});*/
	var img = $('#video' + video_id + ' img').attr('src');
	var watchedHTML = '<li id = "miniVideo' + video_id + '"><a href="#!/video/' + video_id + '"><img src="' + img + '" alt="" width="57" height="36" /></a></li>';
	if ($('.mini-prew #miniVideo' + video_id).size() == 0)
		$(".mini-prew").trigger("insertItem", [watchedHTML, '.mini-prew li:first', true, 0]);
	//e.preventDefault();
}